import asyncio

import aiofile
import aiohttp
import requests


async def download_picture(url):
    async with aiohttp.ClientSession() as session:
        async with session.get(url, ssl=False) as resp:
            data = await resp.read()
            filename = url[url.rfind('/') + 1:]
            async with aiofile.async_open(f'images/{filename}', 'wb') as file:
                await file.write(data)


def main():
    loop = asyncio.get_event_loop()
    for num in range(1, 6):
        resp = requests.get(f'https://image.so.com/zjl?ch=beauty&sn={num * 30}')
        data_dict = resp.json()
        cos_list = []
        for beauty_dict in data_dict['list']:
            picture_url = beauty_dict['qhimg_url']
            cos_list.append(download_picture(picture_url))
        loop.run_until_complete(asyncio.wait(cos_list))
    # loop.close()


if __name__ == '__main__':
    main()
